<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 按钮 -->
    <el-row>
      <el-col>
        <el-button type="primary">添加角色</el-button>
      </el-col>
    </el-row>
    <el-table :data="rolesList" border stripe>
      <!-- 展开列 -->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <!-- 一级列表 -->
          <el-row
            :class="['bottomeBoder', i1 === 0 ? 'topBorder' : '', 'vcenter']"
            v-for="(item1, i1) in scope.row.children"
            :key="item1.id"
          >
            <el-col :span="5"
              ><el-tag
                type="success"
                closable
                @close="removeById(scope.row, item1.id)"
                >{{ item1.authName }}</el-tag
              ><i class="el-icon-caret-right"></i
            ></el-col>
            <!-- 二级 三级 -->
            <el-col :span="19">
              <el-row
                :class="[i2 === 0 ? '' : 'topBorder', 'vcenter']"
                v-for="(item2, i2) in item1.children"
                :key="item2.id"
              >
                <el-col :span="5"
                  ><el-tag
                    type="danger"
                    closable
                    @close="removeById(scope.row, item2.id)"
                    >{{ item2.authName }}</el-tag
                  ><i class="el-icon-caret-right"></i
                ></el-col>
                <el-col :span="19">
                  <span v-for="item3 in item2.children" :key="item3.id">
                    <el-tag
                      type="danger"
                      closable
                      @close="removeById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </span>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <!-- 编辑 -->
          <el-tooltip
            class="item"
            effect="dark"
            content="角色编辑"
            placement="top"
            :enterable="false"
          >
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
            ></el-button>
          </el-tooltip>
          <!-- 删除 -->
          <el-tooltip
            class="item"
            effect="dark"
            content="角色删除"
            placement="top"
            :enterable="false"
          >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
            ></el-button>
          </el-tooltip>
          <!-- 设置 -->
          <el-tooltip
            class="item"
            effect="dark"
            content="分配权限"
            placement="top"
            :enterable="false"
          >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogclosed"
    >
      <!-- 树形结构区域 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        default-expand-all
        show-checkbox
        :default-checked-keys="defKeys"
        ref="treeRef"
        node-key="id"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      setRightDialogVisible: false,
      rolesList: [], // 角色列表
      rightsList: [], // 所有权限列表集合
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      defKeys: [], // 树形默认选中的节点数组
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色权限列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    // 删除指定角色的某个权限
    async removeById(role, rightId) {
      const removeConfirm = await this.$confirm(
        '此操作将永久删除该, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (removeConfirm !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      // this.getRolesList() 导致折叠合上
      // 更新所选角色的最新权限列表
      role.children = res.data
      this.$message.success(res.meta.msg)
    },
    // 点击显示分配权限对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      this.setRightDialogVisible = true
      // 获取该角色权限 树形结构 type = tree
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限失败')
      this.getLeafKeys(role, this.defKeys) // 获取三级节点数据
      this.rightsList = res.data
    },
    // 递归方式 获取三级节点集合数组
    getLeafKeys(node, arr) {
      if (!node.children) return arr.push(node.id)
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 对话框关闭后 默认选中节点清空
    setRightDialogclosed() {
      this.defKeys = []
    },
    // 分配权限后提交
    async setRights() {
      // 获取最新选中的节点 半选择节点
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(), // ...展运符 数组转字符串
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const keysStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: keysStr }
      )
      if (res.meta.status !== 200) return this.$message.error('权限分配失败')
      this.$message.success(res.meta.msg)
      this.getRolesList() // 更新权限列表
      // 关闭弹窗
      this.setRightDialogVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
.topBorder {
  border-top: solid 1px #eee;
}
.bottomeBoder {
  border-bottom: solid 1px #eee;
}
.el-col .el-tag {
  margin: 7px;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
